<template>
  <div class="article-list">

    <van-pull-refresh v-model="isLoading"
                      :success-text="pullText"
                      :success-duration="1000"
                      @refresh="onRefresh">

      <van-list class="article_list"
                v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                :error.sync="error"
                error-text="请求失败，点击重新加载"
                @load="onLoad">

        <article-item v-for="(article, index) in list"
                      :key="index"
                      :article="article" />
      </van-list>
    </van-pull-refresh>
  </div>

</template>

<script>
import { getArticles } from '@/api/article.js'
import ArticleItem from '../../../components/article-item'

export default {
  name: 'ArticleList',
  components: { ArticleItem },
  props: {
    channel: {
      type: Object,
      required: true
    }
  },
  data () {
    return {
      list: [],
      error: false,
      loading: false,
      finished: false,
      isLoading: false,
      pullText: '刷新成功'
    }
  },
  methods: {
    async onLoad () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: this.timestamp || Date.now(),
          with_top: 1
        })
        this.list = data.data.results
        // console.log(data.data.results)
        // console.log(this.list.length)
        this.loading = false
        if (this.list.length >= 10) {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
      }
    },
    async onRefresh () {
      try {
        const { data } = await getArticles({
          channel_id: this.channel.id,
          timestamp: Date.now(),
          with_top: 1
        })
        this.list = data.data.results
        this.isLoading = false
        this.pullText = '刷新成功，数据更新了'
      } catch (err) {
        this.isLoading = false
        this.pullText = '刷新失败， 请重试'
      }
    }
  }
}
</script>

<style  lang="less" scoped >
.van-cell {
  height: 110px;
  line-height: 70px;
}
.article_list {
  height: 79vh;
  overflow-y: auto;
}
</style>
